// 泛型就是可以接收类型的变量

/**
 * 需求：定义一个函数，返回一个数组，要求函数有两个参数，一个参数是value值，一个参数是个数 count
 * 返回的数组是  [value,value,value]  数组的长度是 count
 * 
 * K T V R S   
 * 
 */

function createArr<T>(value: T, count: number): T[] {
    let arr: T[] = [];
    for (let i = 0; i < count; i++) {
        arr.push(value)
    }
    return arr;
}
// createArr('a', 3); // ['a','a','a']   string[]
// createArr(8,4);    // [8,8,8,8]       number[]
console.log(createArr<string>('a', 3))
console.log(createArr<number>(8, 4))


function createTuple<T, K>(a: T, b: K): [T, K] {
    return [a, b]
}

createTuple<string, number>('abc', 99);

createTuple<boolean, number>(true, 77);

// 泛型接口

interface IResponse<T> {
    code: number;
    msg: string,
    data: T
}

interface IBook {
    name: string
    age: number
    intro: string
}

interface ITodo {
    id: number
    title: string
    isDone: boolean
}

let data: IResponse<IBook> = {
    code: 200,
    msg: '获取列表成功',
    data: {
        name: '葵花宝典',
        age: 3000,
        intro: '要想成功'
    }
}

let data2: IResponse<ITodo> = {
    code: 201,
    msg: '创建成功',
    data: {
        id: 1,
        title: '做心理建设',
        isDone: true
    }
}

// 泛型类：用泛型限定类[属性]

class Container<T>{
    store: T[]
    constructor(store: T[]) {
        this.store = store
    }
}

let store = [
    {
        name: '如来神掌',
        age: 5000,
        intro: '如来神掌大成需要童子之身'
    },
    {
        name: '辟邪剑谱',
        age: 3000,
        intro: 'xxxxx'
    }
]

const c1 = new Container<IBook>(store);
console.log(c1.store[0].intro);

// 泛型约束
interface Lengthwise {
    length: number;
}

// 指定泛型约束
function fn2<T extends Lengthwise>(x: T): void {
    console.log(x.length)
}

fn2('123')
fn2([1, 2, 3])


//


